use crate::{config::Config, models::user::{User, UserModel}, utils::jwt, User};
use bcrypt::{hash, verify, DEFAULT_COST};
use tracing::info;
use crate::services::ServiceError;

/// 认证服务结构体
#[derive(Clone)]
pub struct AuthService {
    user_model: UserModel,  // 用户数据操作对象
    config: Config,         // 应用配置
}

impl AuthService {
    pub fn new(user_model: UserModel, config: Config) -> Self {
        Self { user_model, config }
    }

    /// 用户注册服务
    pub async fn register(
        &self,
        username: &str,
        email: &str,
        password: &str,
    ) -> Result<User, crate::services::ServiceError> {
        info!("尝试注册用户: {}", email);

        // 1. 密码哈希处理
        let hashed_password = hash(password, DEFAULT_COST)?;

        // 2. 创建用户记录
        let user = self.user_model
            .create_user(username, email, &hashed_password)
            .await?;

        Ok(user)
    }

    /// 用户登录服务
    pub async fn login(
        &self,
        email: &str,
        password: &str,
    ) -> Result<String, crate::services::ServiceError> {
        info!("尝试登录: {}", email);

        // 1. 查找用户
        let user = self.user_model
            .find_by_email(email)
            .await?
            .ok_or(ServiceError::AuthFailed("用户不存在".into()))?;

        // 2. 验证密码
        let valid = verify(password, &user.password)?;
        if !valid {
            return Err(ServiceError::AuthFailed("密码错误".into()));
        }

        // 3. 生成JWT token
        let token = jwt::generate_token(&user.id.to_string(), &self.config.app)?;

        Ok(token)
    }

    /// 刷新Token服务
    pub async fn refresh_token(
        &self,
        token: &str,
    ) -> Result<String, ServiceError> {
        // 验证旧token
        let claims = jwt::verify_token(token, &self.config.app)?;

        // 生成新token
        let new_token = jwt::generate_token(&claims.sub, &self.config.app)?;

        Ok(new_token)
    }
}